layui.config({
    base: "js/"
}).use(['table', 'layer', 'form', 'jquery'], function () {
    var table = layui.table,
        form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery;


    /***
     *
     * 显示全部用户信息
     *
     */
    table.render({
        elem: '#valueTable'
        , url: '/users/list'
        , cols: [
            [
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', fixed: 'left'}
                , {field: 'uuId', title: 'UUID',}
                , {field: 'userName', title: '用户名',}
                /*, {field: 'password', title: '用户密码',}*/
                , {field: 'email', title: '用户邮箱',}
                , {field: 'registerTime', title: '注册时间',}
                , {field: 'updateTime', title: '修改时间',}
                , {field: 'age', title: '年龄',}
                , {field: 'telephoneNumber', title: '手机号',}
                , {field: 'nickname', title: '用户昵称',}
                , {
                field: 'state', title: '状态', width: 85, templet: function (data) {
                    if (data.state == 0) {
                        return '<div> <input type="checkbox" checked="" name="codeSwitch" lay-skin="switch" id="open" lay-filter="switchTest" switchId=' + data.userId + '' +
                            ' lay-text="启用|已禁用"  value=' + data.state + '></div>';
                    }
                    return '<div> <input type="checkbox" lay-skin="switch" name="codeSwitch"  switchId=' + data.userId + ' lay-filter="switchTest"' +
                        'lay-text="启用|已禁用" value=' + data.state + '></div>';

                }
            }

                , {fixed: 'right', title: '操作', toolbar: '#barDemo'}

            ]
        ]
        , limit: 10
        , limits: [10, 20, 25, 50, 100]
        , parseData: function (data) {
            //打印数据
            console.log(data)
        }

        /**
         * 开启分页
         */
        , page: true
        , where: {state: 0}
        , id: 'linkListReload'
    });

    var $ = layui.$, active = {
        recycleBin: function () {
            var linkReload = $('#linkReload');
            /**
             * 回收站
             * 执行重载
             * 重新从第 1 页开始
             */
            table.reload('linkListReload', {
                page: {
                    curr: 1
                }
                , where: {
                    userName: linkReload.val(),
                    state: 1
                }
            }, 'data');

        }
    }
    /**
     * 回收站
     */
    $('#recycleBin').on('click', function () {
        var layerIndex = layer.load(2);
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
        layer.close(layerIndex);
    });


    /**
     * 监听开关 状态 操作
     * console.log(adminInfoCode + " -- " + (this.checked ? 'true' : 'false'));
     * console.log(data.elem.getAttribute("switchId"))
     * var adminInfoCode = data.value;
     */
    form.on('switch(switchTest)', function (data) {
        /**
         * 禁用标签
         * 状态 赋值为 1
         */
        if ((this.checked ? 'true' : 'false') == 'false') {
            $.ajax({
                url: '/users/delete',
                data: {
                    state: 1,
                    userId: data.elem.getAttribute("switchId")
                },
                type: 'PUT', //HTTP请求类型
                success: function (data) {
                    console.log(data);

                    $.message({
                        message: "禁用用户",
                        type: 'success',
                        showClose: true
                    });

                }, error: function () {
                    $.message({
                        message: "boom..",
                        type: 'error',
                        showClose: true
                    });
                }

            })
        } else {
            /**
             * 启动标签
             * 状态 赋值为 0
             */
            $.ajax({
                url: '/users/delete',
                data: {
                    state: 0,
                    userId: data.elem.getAttribute("switchId")
                },
                type: 'PUT',
                success: function (data) {
                    console.log(data);
                    $.message({
                        message: "启动用户",
                        type: 'success',
                        showClose: true
                    });

                }, error: function () {
                    $.message({
                        message: "boom..",
                        type: 'error',
                        showClose: true
                    });
                }

            })
        }

    });


    /**
     * 添加用户信息
     * 改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
     */
    $(window).one("resize", function () {
        $(".labelsSave").click(function () {
            var index = layui.layer.open({
                title: "添加",
                type: 2,
                content: "./usersSave.html",
                success: function (layero, index) {
                    setTimeout(function () {
                        layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 1000)
                }
            })
            layui.layer.full(index);
        })
    }).resize();

    /**
     * 删除
     */
    table.on('tool(labels)', function (obj) {
        var data = obj.data;
        if (obj.event === 'delLabels') {
            layer.confirm('真的删除行么？', {title: '系统提示'}, function (index) {
                    $.ajax({
                        url: '/users/delete',
                        data: {
                            state: 1,
                            userId: data.userId
                        },
                        type: 'put',
                        success: function (data) {
                            if (data.code == 200) {
                                $.message({
                                    message: data.msg,
                                    type: 'success',
                                    showClose: true
                                });
                                obj.del();
                            } else {
                                $.message({
                                    message: data.msg,
                                    type: 'warning',
                                    showClose: true
                                });
                            }
                        }, error: function () {
                            $.message({
                                message: 'boom..',
                                type: 'error',
                                showClose: true
                            });
                        }, complete: function (XHR, TS) {

                            layer.close(index);
                            layer.close(layerIndex);
                        }
                    })
                }
            );
        } else if (obj.event === 'edit') {

            editLabels(data);
        }
    });

    /**
     *修改用户信息
     */
    function editLabels(data) {
        var index = layui.layer.open({
            title: "修改",
            type: 2,
            content: "./usersUpdate.html",
            success: function (layer, index) {

                var body = layui.layer.getChildFrame('body', index);
                if (data) {

                    /**
                     * 取到弹出层里的元素，并把编辑的内容放进去
                     * 重新渲染表单
                     */
                    body.find("#id").val(data.userId)
                    body.find("#uuId").val(data.userIp);
                    body.find("#userName").val(data.userName);
                    body.find("#password").val(data.password);
                    body.find("#email").val(data.email);
                    body.find("#registerTime").val(data.registerTime);
                    body.find("#updateTime").val(data.updateTime);
                    body.find("#age").val(data.age);
                    body.find("#telephoneNumber").val(data.telephoneNumber);
                    body.find("#nickname").val(data.nickname);
                    body.find("input[name=state][value='0']").attr("checked", data.state == 0 ? true : false);
                    body.find("input[name=state][value='1']").attr("checked", data.state == 1 ? true : false);

                    form.render();

                }

                setTimeout(function () {
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 1000)
            }
        });

        layui.layer.full(index);
    }


    var $ = layui.$, active = {
        /**
         * 批量删除链接
         *
         * */
        closeBtn: function () {
            var $checkbox = $('table input[type="checkbox"][name="layTableCheckbox"]');
            var $checked = $('table input[type="checkbox"][name="layTableCheckbox"]:checked');
            if ($checkbox.is(":checked")) {
                var checkStatusId = table.checkStatus('linkListReload'),
                    data = checkStatusId.data,
                    userId = [];

                for (var i in data) {
                    userId.push(data[i].userId)
                }

                layer.confirm('确定要删除' + data.length + '条数据么?', {title: '系统信息'}, function (index) {
                    var layerIndex = layer.load(2);
                    $.ajax({
                        url: '/users/delBatchUsers',
                        type: 'PUT',
                        data: {
                            state: 1,
                            userId: userId
                        },
                        success: function (res) {
                            if (res.code == 200) {
                                table.reload('linkListReload', {});
                                $.message({
                                    message: res.msg,
                                    type: 'success',
                                    showClose: true
                                });

                            } else {
                                $.message({
                                    message: res.msg,
                                    type: 'warning',
                                    showClose: true
                                });
                            }
                        }, error: function (data) {
                            $.message({
                                message: '系统异常..',
                                type: 'error',
                                showClose: true
                            });
                        }, complete: function () {
                            layer.close(index);
                            layer.close(layerIndex);
                        }
                    })


                })
            } else {
                $.message({
                    message: '请选中要删除的数据',
                    type: 'warning',
                    showClose: true
                });
            }
        },
        reload: function () {
            var linkReload = $('#linkReload');
            console.log(linkReload.val())
            /**
             * 搜索内容
             * 执行重载
             * 重新从第 1 页开始
             */
            table.reload('linkListReload', {
                page: {
                    curr: 1
                }
                , where: {
                    userName: linkReload.val()
                }
            }, 'data');

        }
    };
    $('.batchDel').on('click', function () {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });


    /**
     * 搜索框架 搜索内容
     * @type {*|pe}
     */
    $('.searchBtn').on('click', function () {
        if ($("#linkReload").val() == '') {
            $.message({
                message: '用户名不能为空',
                type: 'warning',
                showClose: true
            });
            return false;
        }

        var layerIndex = layer.load(2);
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
        layer.close(layerIndex);
    });


});